package com.example.robotica.appmobile.utils;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

import org.apache.commons.net.telnet.TelnetClient;

import android.util.Log;

public class Controlador {

	private static final String LOG_TAG = Controlador.class.getSimpleName();
	private TelnetClient telnet;
	private InputStream in;
	private PrintStream out;
	private DataInputStream dataInputStream;
	private static Controlador instancia;

	public Controlador(){
	}
	
	public Controlador(TelnetClient cliente) {
		this.telnet = cliente;
	}
	
	public static Controlador getInstancia(){
		
		if (instancia==null){
			
			instancia 	= new Controlador();
		}
		return instancia;
	}
	
	public void setClienteTelnet(TelnetClient cliente){
		
		this.telnet = cliente;
	}

	public void conectarSocket(String servidor, Integer puerto)
			throws IOException {

		telnet.connect(servidor, puerto);
		in = telnet.getInputStream();
		dataInputStream = new DataInputStream(in);
		out = new PrintStream(telnet.getOutputStream());
		telnet.setKeepAlive(true);
	}

	public void desconectarSocket() throws IOException {
		
		in.close();
		out.close();
		telnet.disconnect();
	}

	public void enviarComando(String comando) {
		
		if (estaConectado()) {
			
			out.println(comando + "\r\n");
			out.flush();		
		}
	}
	
	public float[] leerInformacionSensores() {
		
		float[] informacionLeida = new float[4];
		
		if (estaConectado()) {
			
			try {
				char indicador = dataInputStream.readChar();
				
				//DESCARTO HASTA 10 QUE NO SEAN INDICADORES PARA NO ENTRAR EN UN CICLO INFINITO
				
				for (int i = 0 ; i < 10 && indicador != 'i'  ; i++) {
					indicador = dataInputStream.readChar();
				}
				
				if (indicador == 'i') {
					
					for (int i = 0; i < 4 ; i++) {
						informacionLeida[i] = dataInputStream.readFloat();
					}
				}
			}
			catch (IOException ioe) {
				
				informacionLeida = null;
				Log.w(LOG_TAG, "No se pudieron leer los datos de los sensores" + ioe);
			}
		}
		
		
		return informacionLeida;
	}
	
	public boolean estaConectado() {
		
		return telnet != null && telnet.isConnected();
	}
}
